#include "audio_output_fft.h"
#include "audio.h"

using namespace krryn::audio;

output_fft::output_fft(output::ptr a_Output)
	: m_Output(a_Output), m_Buffer(new value_type[m_Size * 2]) {}

output_fft::~output_fft(){
	delete[] m_Buffer, m_Buffer = 0;
}

int output_fft::sample_rate(){
	return m_Output->sample_rate();
}

void output_fft::write(sample::ptr a_Sample){
	if(!m_Filters.empty()){
		process(a_Sample);
	}

	m_Output->write(a_Sample);
}

void output_fft::process(sample::ptr a_Sample){
	if(a_Sample->count() > m_Size){
		throw exception("Audio sample to large for FFT transformation");
	}

	sample::value_type *l_Temp = a_Sample->buffer();

	for(int i = 0; i < m_Size * 2; i++)
		m_Buffer[i] = 0;

	for(int i = 0; i < a_Sample->count() * 2; i += 2)
		m_Buffer[i] = *l_Temp++;

	m_FFT.transform_forward(m_Buffer);

	for(std::vector<filter::ptr>::iterator i = m_Filters.begin(); i != m_Filters.end(); i++){
		(**i)(m_Buffer, sample_rate(), m_Size);
	}

	m_FFT.transform_inverse(m_Buffer);

	value_type *l_Buffer = m_Buffer;
	l_Temp   = a_Sample->buffer();

	for(int i = 0; i < a_Sample->count(); i+=2){
		*l_Temp++ = l_Buffer[i];
	}
}
